package com.cencat.framework.security.controller;

import com.cencat.common.model.Result;
import com.cencat.framework.security.model.LoginRequest;
import com.cencat.framework.security.model.LoginUser;
import com.cencat.framework.security.service.AuthService;
import com.cencat.framework.security.service.TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final AuthService authService;
    private final TokenService tokenService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginUser> login(@Validated @RequestBody LoginRequest loginRequest) {
        log.info("用户登录请求: username={}", loginRequest.getUsername());
        
        LoginUser loginUser = authService.login(loginRequest);
        
        log.info("用户登录成功: username={}, userId={}", loginRequest.getUsername(), loginUser.getUserId());
        
        return Result.success(loginUser);
    }
    
    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        String token = tokenService.getCurrentLoginUser() != null ? 
            extractToken(request) : null;
        
        if (token != null) {
            authService.logout(token);
            log.info("用户注销: token={}", token);
        }
        
        return Result.success();
    }
    
    /**
     * 刷新令牌
     */
    @PostMapping("/refresh")
    public Result<LoginUser> refreshToken(HttpServletRequest request) {
        String token = extractToken(request);
        
        if (token == null) {
            return Result.error(400, "令牌不能为空");
        }
        
        LoginUser loginUser = authService.refreshToken(token);
        
        log.debug("刷新令牌成功: userId={}", loginUser.getUserId());
        
        return Result.success(loginUser);
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public Result<LoginUser> getCurrentUser() {
        LoginUser loginUser = tokenService.getCurrentLoginUser();
        
        if (loginUser == null) {
            return Result.error(401, "用户未登录");
        }
        
        return Result.success(loginUser);
    }
    
    /**
     * 检查令牌是否有效
     */
    @GetMapping("/check")
    public Result<Boolean> checkToken(HttpServletRequest request) {
        String token = extractToken(request);
        
        if (token == null) {
            return Result.success(false);
        }
        
        boolean isValid = authService.validateToken(token);
        
        return Result.success(isValid);
    }
    
    /**
     * 从请求中提取令牌
     */
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        
        return request.getParameter("token");
    }
}